package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    PermissionDao permissionDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);//分页查询
        Page<Permission> page = permissionDao.selectByName(queryString);
        List<Permission> result = page.getResult();

        long total = page.getTotal();

        PageResult pageResult = new PageResult(total,result);
        return pageResult;
    }

    @Override
    public void add(Permission permission) {
        permissionDao.add1(permission);
    }

    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }


    @Override
    public void delete(Integer id) {
        Long count = permissionDao.findCountByPermissionId(id);
        if (count>0){
            //说明该权限已被其role表关联
            throw new RuntimeException();
        }

        //如果不关联就删除权限
        permissionDao.deleteById(id);
    }
}
